package com.lancer.cloud.auth.handler;

import com.lancer.cloud.common.constants.MqQueueConstants;
import com.lancer.cloud.common.constants.ServiceNameConstants;
import com.lancer.cloud.common.dto.SysLogDto;
import com.lancer.cloud.common.enums.OperationStatusEnum;
import com.lancer.cloud.common.enums.SysLogTypeEnum;
import com.lancer.cloud.common.exception.CustomOauth2Exception;
import com.lancer.cloud.common.util.IpUtils;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * oauth2异常处理器
 *
 * @author caijinbang
 * @date 2019-06-18 19:45
 */
@Slf4j
@Component("customWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseEntity translate(Exception e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String username = request.getParameter("username");
        SysLogDto sysLogDto = new SysLogDto();
        sysLogDto
            .setCreateBy(username)
            .setRequestUri(request.getRequestURI())
            .setUserAgent(IpUtils.getIpAddrByRequest(request))
            .setType(SysLogTypeEnum.LOGIN.getCode().toString())
            .setStatus(OperationStatusEnum.FAIL.getCode().toString())
            .setModuleName("auth认证模块")
            .setActionName("登录")
            .setServiceId(ServiceNameConstants.LANCER_AUTH)
            .setRemoteAddr(IpUtils.getIpAddrByRequest(request))
            .setMethod(request.getMethod())
            .setException(IpUtils.getTrace(e));
        rabbitTemplate.convertAndSend(MqQueueConstants.SYS_LOG_QUEUE, sysLogDto);
        log.error(e.getStackTrace().toString());
        OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
        return ResponseEntity
            .status(HttpStatus.OK)
            .body(new CustomOauth2Exception(oAuth2Exception.getMessage()));
    }
}

